<template>
  <view class="index-container">
    <!-- 顶部状态栏 -->
    <view class="status-bar">
      <view class="user-info">
        <text class="welcome-text">您好，{{userInfo.name || '运营管理员'}}</text>
        <text class="date-text">{{currentDate}}</text>
      </view>
      <view class="notification-icon" @click="goToNotifications">
        <text class="icon">🔔</text>
        <view class="badge" v-if="unreadCount > 0">{{unreadCount}}</view>
      </view>
    </view>

    <!-- 运营数据统计 -->
    <view class="stats-section">
      <view class="section-title">
        <text class="title-text">运营数据概览</text>
        <text class="update-time">更新于 {{updateTime}}</text>
      </view>
      
      <scroll-view class="stats-scroll" scroll-x>
        <view class="stats-grid">
          <view class="stat-card" v-for="stat in statsData" :key="stat.id">
            <view class="stat-icon" :style="{backgroundColor: stat.color}">
              <text class="icon">{{stat.icon}}</text>
            </view>
            <view class="stat-content">
              <text class="stat-value">{{stat.value}}</text>
              <text class="stat-label">{{stat.label}}</text>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 快捷菜单 -->
    <view class="quick-menu-section">
      <view class="section-title">
        <text class="title-text">快捷菜单</text>
      </view>
      
      <view class="menu-grid">
        <view 
          class="menu-item" 
          v-for="menu in quickMenus" 
          :key="menu.id"
          @click="handleMenuClick(menu)"
        >
          <view class="menu-icon" :style="{backgroundColor: menu.color}">
            <text class="icon">{{menu.icon}}</text>
          </view>
          <text class="menu-label">{{menu.label}}</text>
          <view class="menu-badge" v-if="menu.badge">{{menu.badge}}</view>
        </view>
      </view>
    </view>

    <!-- 电柜状态分布 -->
    <view class="status-distribution">
      <view class="section-title">
        <text class="title-text">电柜状态</text>
      </view>
      
      <view class="distribution-chart">
        <view class="chart-item" v-for="item in cabinetStatus" :key="item.status">
          <view class="chart-bar">
            <view 
              class="bar-fill" 
              :style="{
                height: `${item.percentage}%`,
                backgroundColor: item.color
              }"
            ></view>
          </view>
          <view class="chart-label">
            <view class="status-dot" :style="{backgroundColor: item.color}"></view>
            <text class="status-text">{{item.label}}</text>
            <text class="status-count">{{item.count}}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 今日换电趋势 -->
    <view class="trend-section">
      <view class="section-title">
        <text class="title-text">今日换电趋势</text>
        <text class="time-range">今日 00:00 - {{currentTime}}</text>
      </view>
      
      <view class="trend-chart">
        <!-- 简单的柱状图实现 -->
        <view class="chart-bars">
          <view 
            class="bar" 
            v-for="(hour, index) in hourlyData" 
            :key="index"
            :style="{height: `${hour.value}%`}"
          >
            <view class="bar-value">{{hour.value}}</view>
          </view>
        </view>
        <view class="chart-labels">
          <text 
            class="chart-label" 
            v-for="(hour, index) in hourlyData" 
            :key="index"
          >
            {{hour.time}}
          </text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { reportAPI, cabinetAPI } from '@/config/api.js'

export default {
  data() {
    return {
      userInfo: {},
      currentDate: '',
      currentTime: '',
      updateTime: '',
      unreadCount: 0,
      statsData: [
        {
          id: 1,
          icon: '🔋',
          label: '总电柜数',
          value: '待更新',
          trend: 'up',
          color: '#1890ff'
        },
        {
          id: 2,
          icon: '🟢',
          label: '在线电柜',
          value: '待更新',
          trend: 'up',
          color: '#52c41a'
        },
        {
          id: 3,
          icon: '🔄',
          label: '今日换电',
          value: '待更新',
          color: '#faad14'
        },
        {
          id: 4,
          icon: '💰',
          label: '今日收入',
          value: '待更新',
          color: '#f5222d'
        },
        {
          id: 5,
          icon: '⚠️',
          label: '异常设备',
          value: '待更新',
          color: '#fa541c'
        }
      ],
      quickMenus: [
        {
          id: 1,
          icon: '📊',
          label: '电柜管理',
          path: '/pages/index/index',
          color: '#1890ff'
        },
        {
          id: 2,
          icon: '🚪',
          label: '仓门管理',
          path: '/pages/doors/doors',
          color: '#52c41a'
        },
        {
          id: 3,
          icon: '🔋',
          label: '电池监控',
          path: '/pages/index/index',
          color: '#faad14'
        },
  
        {
          id: 4,
          icon: '📈',
          label: '数据报表',
          path: '',
          color: '#13c2c2'
        },
        {
          id: 5,
          icon: '🔧',
          label: '设备维护',
          path: '/pages/fix/fix',
          color: '#fa8c16'
        },
        {
          id: 6,
          icon: '👥',
          label: '用户管理',
          path: '',
          color: '#a0d911'
        }
      ],
      cabinetStatus: [
        {
          status: 'online',
          label: '在线',
          count: 0,
          percentage: 0,
          color: '#52c41a'
        },
        {
          status: 'offline',
          label: '离线',
         count: 0,
         percentage: 0,
          color: '#f5222d'
        },
        {
          status: 'abnormal',
          label: '异常',
          count: 0,
          percentage: 0,
          color: '#faad14'
        },
        {
          status: 'maintenance',
          label: '维护中',
          count: 0,
          percentage: 0,
          color: '#1890ff'
        }
      ],
      hourlyData: [
        { time: '00-02', value: 0 },
        { time: '02-04', value: 0 },
        { time: '04-06', value: 0 },
        { time: '06-08', value: 0 },
        { time: '08-10', value: 0 },
        { time: '10-12', value: 0 },
        { time: '12-14', value: 0 },
        { time: '14-16', value: 0 },
        { time: '16-18', value: 0 },
        { time: '18-20', value: 0 },
        { time: '20-22', value: 0 },
        { time: '22-24', value: 0 }
      ]
    }
  },

  onLoad() {
    this.initData()
    // this.loadStatsData()
  },

  onShow() {
    this.updateTimeInfo()
    // 页面显示时刷新数据
    // this.loadStatsData()
  },

  methods: {
    initData() {
      // 初始化时间信息
      this.updateTimeInfo()
      
      // 获取用户信息
      const userInfo = uni.getStorageSync('userInfo')
      if (userInfo) {
        this.userInfo = userInfo
      }
    },

    updateTimeInfo() {
      const now = new Date()
      this.currentDate = now.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        weekday: 'long'
      })
      
      this.currentTime = now.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      })
      
      this.updateTime = now.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      })
    },

    async loadStatsData() {
      try {
        // 获取运营统计数据
        const statsResult = await reportAPI.getOperationStats({
          date: new Date().toISOString().split('T')[0]
        })
        
        // 获取电柜状态分布
        const statusResult = await cabinetAPI.getCabinetStatusDistribution()
        
        // 更新数据
        if (statsResult) {
          // 根据实际API响应结构更新statsData
          this.statsData[0].value = statsResult.totalCabinets || '156'
          this.statsData[1].value = statsResult.onlineCabinets || '142'
          this.statsData[2].value = statsResult.todayExchanges || '1,248'
          this.statsData[3].value = `¥${statsResult.todayRevenue || '8,560'}`
          this.statsData[4].value = statsResult.abnormalCabinets || '8'
        }
        
        if (statusResult) {
          // 更新电柜状态分布
          this.cabinetStatus = statusResult.distribution || this.cabinetStatus
        }
        
      } catch (error) {
        console.error('加载统计数据失败:', error)
        // 使用默认数据，不显示错误提示
      }
    },

    handleMenuClick(menu) {
      if (menu.path) {
        uni.navigateTo({
          url: menu.path
        })
      } else {
        uni.showToast({
          title: `${menu.label}功能开发中`,
          icon: 'none'
        })
      }
    },

    handleScan() {
      uni.scanCode({
        success: (res) => {
          console.log('扫描结果:', res)
          uni.showToast({
            title: '扫码成功',
            icon: 'success'
          })
          // 处理扫码结果，比如跳转到对应电柜详情
        },
        fail: (err) => {
          console.error('扫码失败:', err)
          uni.showToast({
            title: '扫码失败',
            icon: 'none'
          })
        }
      })
    },

    goToWorkbench() {
      uni.switchTab({
        url: '/pages/workbench/workbench'
      })
    },

    goToCabinetList() {
      uni.navigateTo({
        url: '/pages/index/index'
      })
    },

    goToNotifications() {
      uni.showToast({
        title: '暂未开放',
        icon: 'none'
      })
    }
  }
}
</script>

<style scoped>
.index-container {
  background: linear-gradient(180deg, #f5f7fa 0%, #ffffff 100%);
  min-height: 100vh;
  padding-bottom: 120rpx;
}

/* 顶部状态栏 */
.status-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 40rpx 30rpx 20rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.user-info {
  flex: 1;
}

.welcome-text {
  display: block;
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 8rpx;
}

.date-text {
  font-size: 26rpx;
  opacity: 0.9;
}

.notification-icon {
  position: relative;
  padding: 20rpx;
}

.notification-icon .icon {
  font-size: 40rpx;
}

.badge {
  position: absolute;
  top: 15rpx;
  right: 15rpx;
  background: #ff4d4f;
  color: white;
  border-radius: 20rpx;
  min-width: 30rpx;
  height: 30rpx;
  font-size: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 8rpx;
}

/* 区块标题 */
.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 30rpx 20rpx;
}

.title-text {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.update-time,
.more-link,
.time-range {
  font-size: 24rpx;
  color: #999;
}

.more-link {
  color: #1890ff;
}

/* 运营数据统计 */
.stats-section {
  background: white;
  margin: 20rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.06);
}

.stats-scroll {
  white-space: nowrap;
  padding: 0 20rpx 30rpx;
}

.stats-grid {
  display: inline-flex;
  gap: 20rpx;
}

.stat-card {
  display: inline-flex;
  align-items: center;
  background: #fafafa;
  border-radius: 16rpx;
  padding: 30rpx;
  min-width: 280rpx;
}

.stat-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20rpx;
}

.stat-icon .icon {
  font-size: 36rpx;
}

.stat-content {
  flex: 1;
}

.stat-value {
  display: block;
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 8rpx;
}

.stat-label {
  display: block;
  font-size: 24rpx;
  color: #666;
  margin-bottom: 8rpx;
}

.stat-trend {
  display: flex;
  align-items: center;
  font-size: 22rpx;
}

.stat-trend.up {
  color: #52c41a;
}

.stat-trend.down {
  color: #f5222d;
}

.trend-icon {
  margin-right: 4rpx;
}

/* 快捷菜单 */
.quick-menu-section {
  background: white;
  margin: 20rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.06);
}

.menu-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 30rpx;
  padding: 0 30rpx 40rpx;
}

.menu-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}

.menu-icon {
  width: 100rpx;
  height: 100rpx;
  border-radius: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 16rpx;
  transition: all 0.3s ease;
}

.menu-item:active .menu-icon {
  transform: scale(0.95);
}

.menu-icon .icon {
  font-size: 40rpx;
}

.menu-label {
  font-size: 24rpx;
  color: #333;
  text-align: center;
}

.menu-badge {
  position: absolute;
  top: -10rpx;
  right: 0;
  background: #ff4d4f;
  color: white;
  border-radius: 20rpx;
  min-width: 36rpx;
  height: 36rpx;
  font-size: 22rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 8rpx;
}

/* 电柜状态分布 */
.status-distribution {
  background: white;
  margin: 20rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.06);
}

.distribution-chart {
  display: flex;
  justify-content: space-around;
  align-items: flex-end;
  padding: 0 30rpx 40rpx;
  height: 200rpx;
}

.chart-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
}

.chart-bar {
  width: 40rpx;
  height: 120rpx;
  background: #f0f0f0;
  border-radius: 8rpx;
  position: relative;
  margin-bottom: 20rpx;
}

.bar-fill {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  border-radius: 8rpx;
  transition: height 0.5s ease;
}

.chart-label {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.status-dot {
  width: 16rpx;
  height: 16rpx;
  border-radius: 50%;
  margin-bottom: 8rpx;
}

.status-text {
  font-size: 22rpx;
  color: #666;
  margin-bottom: 4rpx;
}

.status-count {
  font-size: 24rpx;
  font-weight: bold;
  color: #333;
}

/* 今日换电趋势 */
.trend-section {
  background: white;
  margin: 20rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 20rpx rgba(0,0,0,0.06);
}

.trend-chart {
  padding: 0 30rpx 40rpx;
}

.chart-bars {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  height: 160rpx;
  margin-bottom: 20rpx;
}

.bar {
  flex: 1;
  background: linear-gradient(180deg, #1890ff 0%, #096dd9 100%);
  border-radius: 4rpx 4rpx 0 0;
  margin: 0 4rpx;
  position: relative;
  min-height: 20rpx;
  transition: height 0.5s ease;
}

.bar-value {
  position: absolute;
  top: -40rpx;
  left: 50%;
  transform: translateX(-50%);
  font-size: 20rpx;
  color: #666;
  white-space: nowrap;
}

.chart-labels {
  display: flex;
  justify-content: space-between;
}

.chart-label {
  flex: 1;
  text-align: center;
  font-size: 20rpx;
  color: #999;
}

/* 底部操作栏 */
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 20rpx 30rpx;
  display: flex;
  gap: 20rpx;
  border-top: 1rpx solid #f0f0f0;
  box-shadow: 0 -4rpx 20rpx rgba(0,0,0,0.06);
}

.action-btn {
  flex: 1;
  height: 100rpx;
  border-radius: 50rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  font-weight: bold;
  border: none;
}

.scan-btn {
  background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
  color: white;
}

.workbench-btn {
  background: #f5f5f5;
  color: #333;
  border: 1rpx solid #e8e8e8;
}

.btn-icon {
  margin-right: 12rpx;
  font-size: 36rpx;
}
</style>